package cn.cuilan.server;

import cn.cuilan.common.entity.ProtocolMessage;
import cn.cuilan.common.server.ProtocolMessageServer;
import cn.cuilan.server.core.NetServerMessageProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Slf4j
@SpringBootApplication
public class ServerApplication implements CommandLineRunner {

    @Resource
    private ProtocolMessageServer<ProtocolMessage> server;

    @Resource
    private NetServerMessageProcessor netServerMessageProcessor;

    @Override
    public void run(String... args) throws Exception {
    }

    @PostConstruct
    public void startUp() throws InterruptedException {
        // 添加消息处理器
        server.addMessageListener(netServerMessageProcessor);
        // 配置服务端
        server.getConfiguration().replyOnError();
        // 初始化
        server.init();
        // 启动服务
        server.start();
    }

    @PreDestroy
    public void close() {
        log.info("Net Server is closed!");
        server.shutdown();
    }

    public static void main(String[] args) {
        SpringApplication.run(ServerApplication.class, args);
    }


}
